package com.novel.disk.controller;

import com.novel.disk.common.*;
import com.novel.disk.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 图片资源预览接口
 *
 * @author novel
 * @date 2020/7/28
 */
@RestController
@Slf4j
@RequestMapping(Constants.FILE_CONTL)
public class StaticFileController extends BaseController {
    private final FileService fileService;

    public StaticFileController(FileService fileService) {
        this.fileService = fileService;
    }

    @GetMapping(value = "/preview")
    @CrossOrigin(
            origins = "*",
            methods = {RequestMethod.GET}
    )
    public ResponseEntity<Object> preview(@RequestParam(name = "uri") String url, @RequestParam(name = "name") String name, @RequestHeader("user-agent") String userAgent, @RequestParam(name = "exp", required = false) Long exp, @RequestParam(name = "w", required = false) Integer w, @RequestParam(name = "h", required = false) Integer h) throws Exception {
        File file = fileService.readBytes(url);
        byte[] bytesByFile = FileUtils.getBytesByFile(file);
        if (w != null && w > 0 && h != null && h > 0) {
            //如果前端传来图片的宽高，那么则对返回的图片进行压缩
            bytesByFile = ImageUtils.resize(bytesByFile, w, h, false);
        }
        ContentDisposition contentDisposition = ContentDisposition.builder("inline").filename(FileUtils.setFileDownloadHeader(userAgent, name)).build();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(contentDisposition);
        headers.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30));
        Tika tika = new Tika();
        String contentType = tika.detect(file);
        if (StringUtils.isNotEmpty(contentType)) {
            MediaType mediaType = new MediaType(MediaType.parseMediaType(contentType), Charset.forName(FileUtils.charset(file)));
            headers.setContentType(mediaType);
        } else {
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        }
        return ResponseEntity.ok()
                .headers(headers)
                .cacheControl(CacheControl.maxAge(Duration.ofDays(30)))
                .contentLength(Objects.requireNonNull(bytesByFile).length)
                .body(bytesByFile);
    }
}
